import moment from "moment"
import { uploadtoqiniu } from "@/api/users.js"
import lrz from "lrz"
import { useBaseStore } from "@/store/Base.js"

/* 深拷贝 */
function deepClone(obj) {
  //判断传进来的参数类型不是对象数组 或者是null时 直接返回
  if (typeof obj !== "object" || obj == null) {
    return obj
  }
  //定义返回值result
  // 判断传进来的数据类型 是数组/对象 就给result一个数组/对象
  let result = Array.isArray(obj) ? [] : {};
  //循环遍历方便拷贝
  for (let key in obj) {
    //判读自有属性
    if (obj.hasOwnProperty(key)) {
      //函数递归实现深层拷贝
      result[key] = deepClone(obj[key])
    }
  }
  //返回出去
  return result
}

/* 七牛云上传 */
async function uploadqiniu(uploadimglist, coverflagname="") {
  let baseStore = useBaseStore()
  let PromiseList = []
  /* 对数据进行压缩 和  上传七牛云*/
  for (let i = 0; i < uploadimglist.length; i++) {
    let item = uploadimglist[i];
    if(!(item?.raw instanceof File) && !(item instanceof File)){
      console.log("not",item);
      continue;
    }
    try {
      let rst = await lrz(item?.raw ?? item)
      // 处理成功会执行
      const config = {
        headers: { 'Content-Type': 'multipart/form-data' }
      }
      let filetype = ''
      if (rst.file.type === 'image/png') {
        filetype = 'png'
      } else {
        filetype = 'jpg'
      }
      // 重命名要上传的文件
      const keyname = (item?.iscover ? `-${coverflagname}-` : "") + moment().format('YYYYMMDDHHmmssss') + Number.parseInt(Math.random() * 1000, 10) + '.' + filetype
      const formdata = new FormData()
      formdata.append('file', rst.file)
      formdata.append('token', baseStore.qiniuToken)
      formdata.append('key', keyname)
      PromiseList.push(uploadtoqiniu(formdata, config))

    } catch (error) {
      console.log(error);
      ElMessage({
        message: '上传照片错误',
        type: 'warning',
      })
    }
  }
  let ress = await Promise.all(PromiseList).then((result) => {
    return result
  }).catch((error) => {
    console.log(error)      // 失败了，打出 '失败'
  })
  return ress
}

/* 获取随机字符串 */
function randomString(len) {
  len = len || 4;
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = $chars.length;
  var pwd = '';
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

export {
  deepClone,
  uploadqiniu,
  randomString
}